package com.ihtry.controller;

import com.ihtry.pojo.Admin;
import com.ihtry.service.AdminService;
import com.ihtry.utils.Code;
import com.ihtry.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//RESTful风格
@RestController
@RequestMapping("/admins")
public class AdminController {
    //自动装配
    @Autowired
    private AdminService adminService;

    /**
     * 登录
     */
    @RequestMapping("/login")
    public Result login(@RequestBody Admin admin) {
        Admin login = adminService.login(admin);
        String msg = login != null ? "登录成功" : "登录信息错误!";
        Integer code = login != null ? Code.LOGIN_OK : Code.LOGIN_ERR;
        return new Result(code, msg, null);
    }


    /**
     * 注册
     */
    @PostMapping
    public Result reg(@RequestBody Admin admin) {
        //判断用户名是否存在
        Admin username = adminService.getAdminByUsername(admin.getUsername());

        //不等于null就存在->false 等于null->true
        boolean status = username == null;
        //如果不存在，则执行注册
        if (status) {
            adminService.reg(admin);
        }
        String msg = status ? "注册成功" : "用户名已存在!";
        return new Result(status ? Code.REG_OK : Code.REG_ERR, msg, null);
    }


    /**
     * 查询全部用户
     */
    @RequestMapping("/get")
    public Result getAll() {
        List<Admin> adminList = adminService.getAll();
        //查询列表是否为空
        Integer code = adminList != null ? Code.GET_OK : Code.GET_ERR;
        String msg = adminList != null ? "查询成功" : "查询失败";
        return new Result(code, msg, adminList);
    }


    /**
     * 通过id查询
     */
    @GetMapping("/{id}")
    public Result getAdminById(@PathVariable Integer id) {
        Admin admin = adminService.getAdminById(id);
        //查询列表是否为空
        Integer code = admin != null ? Code.GET_OK : Code.GET_ERR;
        String msg = admin != null ? "查询成功" : "查询失败";
        return new Result(code, msg, admin);
    }


    /**
     * 修改用户
     */
    @PutMapping
    public Result updateAdmin(@RequestBody Admin admin) {
        boolean updateAdmin = adminService.updateAdmin(admin);
        String msg = updateAdmin ? "修改成功" : "修改失败";
        return new Result(updateAdmin ? Code.UPDATE_OK : Code.UPDATE_ERR, msg, null);
    }


    /**
     * 根据id删除用户
     */
    @DeleteMapping("/{id}")
    public Result deleteAdmin(@PathVariable Integer id) {
        boolean deleteAdmin = adminService.deleteAdmin(id);
        String msg = deleteAdmin ? "删除成功" : "删除失败";
        return new Result(deleteAdmin ? Code.DELETE_OK : Code.DELETE_ERR, msg, null);
    }


}
